package com.eastcom.groovy.task.taskdirector.temp

import java.awt.TexturePaintContext.Int;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress.Cache;
import java.sql.Date;
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eastcom.groovy.tools.common.JmsJndiConfig
import com.eastcom.groovy.tools.common.MQCommunication
import com.eastcom.groovy.tools.common.ShellExecutor;
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.file.FileUtils;
import com.eastcom.groovy.tools.file.FtpUtils;
import com.eastcom.groovy.provider.*
import com.eastcom.groovy.tools.mail.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.util.ClassPath.Dir;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.apache.tools.ant.types.FileList;
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
class SimpleTxtFileTaskDirector_Ftp_Email_RaduisConfigFile {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String[] ftpRemotePath = [
		"/home/dongxin/lm1",
		"/home/dongxin/lm2",
		"/home/dongxin/portal1",
		"/home/dongxin/portal2",
		"/home/dongxin/portal3",
		"/home/dongxin/portal4",
		"/home/dongxin/portal5",
		"/home/dongxin/portal6",
		"/home/dongxin/portal7",
		"/home/dongxin/radius1",
		"/home/dongxin/radius2",
		"/home/dongxin/radius3",
		"/home/dongxin/radius4",
		"/home/dongxin/radius5",
		"/home/dongxin/radius6",
		"/home/dongxin/mdb1",
		"/home/dongxin/mdb2",
		"/home/dongxin/obs1",
		"/home/dongxin/obs2"]
	final String[] ftpLocalPath = [
		"/home/ipnet/mystope/allconfig/lm1",
		"/home/ipnet/mystope/allconfig/lm2",
		"/home/ipnet/mystope/allconfig/portal1",
		"/home/ipnet/mystope/allconfig/portal2",
		"/home/ipnet/mystope/allconfig/portal3",
		"/home/ipnet/mystope/allconfig/portal4",
		"/home/ipnet/mystope/allconfig/portal5",
		"/home/ipnet/mystope/allconfig/portal6",
		"/home/ipnet/mystope/allconfig/portal7",
		"/home/ipnet/mystope/allconfig/radius1",
		"/home/ipnet/mystope/allconfig/radius2",
		"/home/ipnet/mystope/allconfig/radius3",
		"/home/ipnet/mystope/allconfig/radius4",
		"/home/ipnet/mystope/allconfig/radius5",
		"/home/ipnet/mystope/allconfig/radius6",
		"/home/ipnet/mystope/allconfig/mdb1",
		"/home/ipnet/mystope/allconfig/mdb2",
		"/home/ipnet/mystope/allconfig/obs1",
		"/home/ipnet/mystope/allconfig/obs2"
	]
	final String[][] ftpFileNameRegex =
	[
		["lm.ini\\.(\\d+)"],
		["lm.ini\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["configuration\\.xml\\.(\\d+)"],
		["configuration\\.xml\\.(\\d+)"],
		["aiip\\.cfg\\.(\\d+)"],
		["aiip\\.cfg\\.(\\d+)"]
	]
	//没有时间的话用[]
	final String[][] fileNameTimeFormat =
	[
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"]
	]
	final String ftpIp = "10.11.244.119"
	final String ftpUser = "dongxin"
	final String ftpPasswd = "dx@wlan"
	final int ftpPort = 21
	final int ftpFileLimit = 200
	final String ftpSystem = "UNIX"
	final String ftpControlEnCode = "UTF-8"
	final String ftpFileEnCode = "UTF-8"
	final String ftpServerLanguage = "zh"
	final long fileLimit = 20000000000
	final String dstdbBean = "oracle_39_nhm"
	final String sql = "insert into EMAIL_ATTACHMENT_FILE(TIMESTAMP,DEVICEIP,DEVICETYPE,FILETYPE,FILENAME,FILEFTPSERVERPATH,FILECONTEXT) values(?,?,?,?,?,?,?)"
	int[] sqlTypes = [Types.TIMESTAMP,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.CLOB]
	final String attachMentDir = "/home/ipnet/mystope/allconfig_email"
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static Log logger = LogFactory.getLog(SimpleTxtFileTaskDirector_Ftp_Email_RaduisConfigFile.class)



	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){

	}

	public boolean doJob(String jobId){
		try {
			File attachDir = new File(attachMentDir)
			if(attachDir.isDirectory()){
				ShellExecutor sh = new ShellExecutor("rm -r "+attachMentDir, false)
				sh.exec()
				logger.debug("删除旧的配置文件目录！")
			}
		} catch (Exception e) {
			e.printStackTrace()
		}

		doFtp()
		try {
			File dir = new File(attachMentDir)
			File[] dirList = dir.listFiles()
			dirList.each {
				doSaveAttachment(it)
			}
		} catch (Exception e) {
			e.printStackTrace()
		}
	}

	private boolean doFtp(){
		try{
			FTPFile[] acceptFiles = null;
			FtpUtils ftpUtils = new FtpUtils();
			for(int i = 0; i < ftpRemotePath.length; i++){
				String rp = ftpRemotePath[i]
				String lp = ftpLocalPath[i]
				File dirFile = new File(lp);
				if(! dirFile.exists()){
					dirFile.mkdirs();
				}
				ftpUtils.login(ftpIp, ftpPort, ftpUser, ftpPasswd, ftpSystem, ftpControlEnCode, ftpServerLanguage);
				ftpUtils.getFtp().changeWorkingDirectory(rp);
				String[] fileNameRegex = ftpFileNameRegex[i]
				String[] fileTimeFormat = fileNameTimeFormat[i]
				for(int j = 0; j < fileNameRegex.length; j++){
					String nameRegex = fileNameRegex[j]
					println nameRegex

					String timeFormat = fileTimeFormat[j]
					Pattern pat = Pattern.compile(nameRegex);
					acceptFiles = ftpUtils.getFtp().listFiles(null, new FTPFileFilter() {
								private int fileCount = 0;
								@Override
								public boolean accept(FTPFile file) {
									// TODO 自动生成的方法存根
									String name = file.getName();
									println name

									Matcher mat = pat.matcher(name);
									boolean rs = mat.find();
									if(! rs){
										return false
									}
									String tm = mat.group(1)
									SimpleDateFormat simp = new SimpleDateFormat(timeFormat)
									java.util.Date date = simp.parse(tm)
									Calendar fileLimitTime = Calendar.getInstance();
									fileLimitTime.setTimeInMillis(new java.util.Date().getTime() - fileLimit);
									if(date.before(fileLimitTime.getTime())){
										return false
									}
									File localFile = new File(lp);
									String[] localFiles = localFile.list();
									if(localFiles != null){
										for(String lf: localFiles){
											if(lf.equalsIgnoreCase(name)){
												return false;
											}
										}
									}

									if(fileCount > ftpFileLimit){
										return false;
									}
									fileCount++;
									return true;
								}
							});
					boolean res = false;
					int count = 0;
					System.out.println("接收的文件数量："+acceptFiles.length);
					for(int k = 0; k < acceptFiles.length; k++){
						String fileName = acceptFiles[k].getName();
						File f = null;
						String dir = lp

						if(dir.endsWith("/")||dir.endsWith("\\")||dir.endsWith("\\\\")){
							f=new File(dir+fileName);
						}else{
							f=new File(dir+"/"+fileName);
						}
						OutputStream os=new FileOutputStream(f);
						res = ftpUtils.getFtp().retrieveFile(new String(fileName.getBytes(ftpFileEnCode),"ISO-8859-1"), os);
						if(res){
							count ++;
						}
						os.flush()
						os.close()
						logger.debug("下载了"+count+"文件！")
						cpFileToDir(f,lp)

					}
				}

			}
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private void cpFileToDir(File f,String lp){
		String[] tempDir = lp.split("/")
		String subDir = tempDir[tempDir.length-1]
		File targetDir = new File(attachMentDir+"/"+subDir)
		if(! targetDir.isDirectory()){
			targetDir.mkdirs()
		}
		FileUtils.copyFile(f, new File(attachMentDir+"/"+subDir+"/"+f.getName()))
		logger.debug("备份了"+lp+"下的"+f.getName()+"文件到"+attachMentDir+"目录中。")
	}


	private boolean doSaveAttachment(File dir){
		File[] fileList = dir.listFiles()
		String dirName = dir.getName()
		final OracleLobHandler lobHandler = new OracleLobHandler()
		CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
		lobHandler.setNativeJdbcExtractor(extractor);
		if(fileList == null){
			return false
		}
		fileList.each {
			String deviceIp
			String deviceType
			String fileType
			String fileName= it.getName()
			String fileFtpServerPath = "/home/dongxin/"+dir.getName()
			String[] temp = fileName.split("\\.")
			fileType = temp[0]+"."+temp[1]
			String fileContext = getFileContext(it)
			if(dirName.contains("lm")){
				if(dirName.equals("lm1")){
					deviceIp = "10.11.244.68"
					deviceType = "LM"
				}else if(dirName.equals("lm2")){
					deviceIp = "10.11.244.71"
					deviceType = "LM"
				}
			}else if(dirName.contains("portal")){
				deviceType = "PORTAL"
				String index = dirName.substring(dirName.length()-1, dirName.length())
			}else if(dirName.contains("radius")){
				deviceType = "RADIUS"
				String index = dirName.substring(dirName.length()-1, dirName.length())
				deviceIp = "10.11.209.4"+index
			}else if(dirName.contains("mdb")){
				deviceType = "MDB"
				if(dirName.equals("mdb1")){
					deviceIp ="10.11.209.17"
				}else if(dirName.equals("mdb2")){
					deviceIp ="10.11.209.20"
				}
			}else if(dirName.contains("obs")){
				deviceType = "OBS"
				if(dirName.equals("obs1")){
					deviceIp ="10.11.245.4"
				}else if(dirName.equals("obs2")){
					deviceIp ="10.11.245.7"
				}
			}
			try {
				DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
				dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
				dbEngine.getJdbcUtil().execute(sql, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
							protected void setValues(PreparedStatement pstmt, LobCreator lobCreator)
							throws SQLException, DataAccessException {
								Timestamp date = new Timestamp(new java.util.Date().getTime())
								pstmt.setTimestamp(1, date)
								pstmt.setString(2, deviceIp)
								pstmt.setString(3, deviceType)
								pstmt.setString(4, fileType)
								pstmt.setString(5, fileName)
								pstmt.setString(6, fileFtpServerPath)
								lobCreator.setClobAsString(pstmt,7,fileContext)
							}
						})
			} catch (Exception e) {
				e.printStackTrace()
			}


		}
		logger.debug("已经保存文件！")
		return true
	}

	private String getFileContext(File file){
		return FileUtils.readFileToString(file,"GBK")
	}
}